package com.adk.backend.service.impl;

import com.adk.backend.common.PageResult;
import com.adk.backend.entity.LxPackingList;
import com.adk.backend.mapper.PackingListMapper;
import com.adk.backend.service.PackingListService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 装箱单列表服务实现类
 */
@Slf4j
@Service
public class PackingListServiceImpl extends ServiceImpl<PackingListMapper, LxPackingList> implements PackingListService {
    
    @Autowired
    private PackingListMapper packingListMapper;
    
    @Override
    public PageResult<LxPackingList> getPackingList(Map<String, Object> params) {
        Integer pageNum = (Integer) params.getOrDefault("pageNum", 1);
        Integer pageSize = (Integer) params.getOrDefault("pageSize", 20);
        
        QueryWrapper<LxPackingList> wrapper = new QueryWrapper<>();
        
        // 按订单ID筛选
        if (params.get("orderId") != null) {
            wrapper.eq("order_id", params.get("orderId"));
        }
        
        // 按箱号筛选
        if (params.get("ctnNo") != null) {
            wrapper.eq("ctn_no", params.get("ctnNo"));
        }
        
        // 按产品名称模糊查询
        if (params.get("proName") != null && !params.get("proName").toString().isEmpty()) {
            wrapper.like("pro_name", params.get("proName"));
        }
        
        // 按SKU查询
        if (params.get("sku") != null && !params.get("sku").toString().isEmpty()) {
            wrapper.like("sku", params.get("sku"));
        }
        
        wrapper.orderByAsc("order_id", "ctn_no");
        
        Page<LxPackingList> page = new Page<>(pageNum, pageSize);
        Page<LxPackingList> result = packingListMapper.selectPage(page, wrapper);
        
        PageResult<LxPackingList> pageResult = new PageResult<>();
        pageResult.setList(result.getRecords());
        pageResult.setTotal(result.getTotal());
        pageResult.setPageNum(pageNum);
        pageResult.setPageSize(pageSize);
        pageResult.setTotalPages((int) result.getPages());
        
        return pageResult;
    }
    
    @Override
    public List<LxPackingList> getPackingListByOrderId(Long orderId) {
        QueryWrapper<LxPackingList> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id", orderId);
        wrapper.orderByAsc("ctn_no");
        return packingListMapper.selectList(wrapper);
    }
    
    @Override
    public LxPackingList getPackingById(Long id) {
        return packingListMapper.selectById(id);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public LxPackingList createPacking(LxPackingList packingList) {
        // 计算小计
        if (packingList.getQty() != null && packingList.getUnitPrice() != null) {
            BigDecimal subTotal = packingList.getUnitPrice().multiply(new BigDecimal(packingList.getQty()));
            packingList.setSubTotal(subTotal);
        }
        
        // 计算箱体积重
        if (packingList.getCtnL() != null && packingList.getCtnW() != null && packingList.getCtnH() != null) {
            // 体积重 = 长 * 宽 * 高 / 5000 (空运) 或 / 6000 (海运)
            BigDecimal volume = new BigDecimal(packingList.getCtnL())
                    .multiply(new BigDecimal(packingList.getCtnW()))
                    .multiply(new BigDecimal(packingList.getCtnH()));
            // 默认使用5000（空运标准）
            BigDecimal volumeWeight = volume.divide(new BigDecimal(5000), 2, BigDecimal.ROUND_HALF_UP);
            packingList.setCtnVw(volumeWeight);
        }
        
        packingListMapper.insert(packingList);
        return packingList;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updatePacking(LxPackingList packingList) {
        // 计算小计
        if (packingList.getQty() != null && packingList.getUnitPrice() != null) {
            BigDecimal subTotal = packingList.getUnitPrice().multiply(new BigDecimal(packingList.getQty()));
            packingList.setSubTotal(subTotal);
        }
        
        // 计算箱体积重
        if (packingList.getCtnL() != null && packingList.getCtnW() != null && packingList.getCtnH() != null) {
            BigDecimal volume = new BigDecimal(packingList.getCtnL())
                    .multiply(new BigDecimal(packingList.getCtnW()))
                    .multiply(new BigDecimal(packingList.getCtnH()));
            BigDecimal volumeWeight = volume.divide(new BigDecimal(5000), 2, BigDecimal.ROUND_HALF_UP);
            packingList.setCtnVw(volumeWeight);
        }
        
        return packingListMapper.updateById(packingList) > 0;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deletePacking(Long id) {
        return packingListMapper.deleteById(id) > 0;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchCreatePacking(List<LxPackingList> packingList) {
        for (LxPackingList packing : packingList) {
            createPacking(packing);
        }
        return true;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchUpdatePacking(List<LxPackingList> packingList) {
        for (LxPackingList packing : packingList) {
            updatePacking(packing);
        }
        return true;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deletePackingByOrderId(Long orderId) {
        QueryWrapper<LxPackingList> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id", orderId);
        return packingListMapper.delete(wrapper) > 0;
    }
}

